<!--
 * @Author: zhayang
 * @LastEditors: zhayang 1063975710@qq.com
 * @Date: 2024-06-28 22:00:20
 * @LastEditTime: 2024-07-03 21:58:50
 * @Description: 视频列表
-->
<template>
  <div class="fit column">
    <div class="video-list-header h-col-auto flex justify-between">
      <el-button
        type="primary"
        size="small"
        icon="el-icon-plus"
        :loading="loading"
        @click="turnTo"
      >
        添加视频
      </el-button>
      <el-button
        size="small"
        :loading="loading"
        :disabled="isShow"
        @click="openShow('relation')"
      >
        关联合集
      </el-button>
      <el-button
        size="small"
        :loading="loading"
        :disabled="isShow"
        @click="openShow('delete')"
      >
        删除
      </el-button>
      <div class="flex justify-end h-col">
        <div class="w-300">
          <el-input
            v-model="searchVal"
            placeholder="输入视频名称"
            clearable
            size="small"
            @keydown.enter.native="search"
          >
            <i
              slot="suffix"
              class="el-icon-search el-input__icon"
            ></i>
          </el-input>
        </div>
        <div class="m-l-10">
          <el-button
            type="primary"
            size="small"
            :loading="loading"
            @click="search"
          >
            查询
          </el-button>
        </div>
      </div>
    </div>
    <div
      class="video-list-body h-col m-t-14 flex flex-col flex-nowrap overflow-auto"
    >
      <div
        v-if="!videoList.length"
        class="full-w h-240 bg-#F4F5F9 cursor-pointer center column rd-4"
        @click="turnTo"
      >
        <div class="h-40 h-40 m-b-20">
          <img
            :src="require('@/assets/images/video/video-plus.png')"
            class="fit"
          />
        </div>
        <div class="text-#1C1D23 text-20 line-height-23 font-600 m-b-4">
          添加视频
        </div>
        <div class="text-#9e9e9e text-12 line-height-14">
          还没有视频，点击添加视频
        </div>
      </div>
      <videoCard
        v-for="item in videoList"
        :key="item.id"
        :is-do="isShow"
        :data="item"
        :is-checked="checkedList.includes(item.id)"
        @delete="deleteVideo"
        @check="checkedPush"
        @open="openVideo"
      />
    </div>
    <el-dialog
      title="关联合集"
      :visible.sync="visible"
      width="30%"
      center
    >
      <div class="text-#1C1F23 line-height-16 text-14 m-b-12 font-600">
        为选择的{{ checkedList.length }}个视频，分配合集
      </div>
      <div class="text-#1C1F23 line-height-16 text-14 m-b-8">选择合集</div>
      <Select
        v-model="series_id"
        placeholder="请选择合集"
        size="medium"
        style="width: 100%"
        :options="options"
      />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="visible = false"
        >
          取 消
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="confirmSave"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
    <transition name="el-fade-in-linear">
      <div
        v-if="videoShow"
        class="model-mask z-9998 fit fixed left-0 top-0 bg-#00000080 overflow-hidden center"
        @click.stop="closeMask"
      >
        <div @click.stop>
          <video
            class="model-video z-9999 fit"
            :src="videoUrl"
            controls
          ></video>
        </div>
      </div>
    </transition>
    <div
      v-if="isShow"
      class="video-list-footer h-col-auto flex justify-center"
    >
      <el-button
        size="small"
        :loading="loading"
        @click="cancel"
      >
        取消
      </el-button>
      <el-button
        type="primary"
        size="small"
        :loading="loading"
        @click="save"
      >
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
import videoCard from '@/components/bmp/card/video-card.vue'
import {
  getVideoList,
  getCollectList,
  deleteSingleVideo,
  linkSeries
} from '@/api/video'
import { Select } from '@/components/bmp/form/index'
import { Loading } from 'element-ui'
export default {
  components: {
    videoCard,
    Select
  },
  data() {
    return {
      loading: false,
      visible: false,
      searchVal: '',
      videoList: [],
      dataList: [],
      isShow: false,
      type: 'relation',
      checkedList: [],
      series_id: '',
      videoUrl: '',
      options: [],
      videoShow: false
    }
  },
  created() {
    this.getData()
  },
  methods: {
    turnTo() {
      this.$router.push({
        path: 'add-video'
      })
    },
    getData() {
      this.loading = true
      const loadingInstance = Loading.service()
      getVideoList()
        .then((res) => {
          if (res && res.code === 0) {
            this.videoList = res.data
            this.dataList = res.data
          }
        })
        .catch(() => {
          this.$message.error('获取错误，请重试')
        })
        .finally(() => {
          this.loading = false
          this.$nextTick(() => {
            loadingInstance.close()
          })
        })
    },
    openShow(type) {
      if (!this.isShow) {
        this.isShow = true
        this.type = type
      }
    },
    cancel() {
      this.isShow = false
      this.checkedList = []
    },
    // 删除单一视频promise形式
    fetchRequest(id) {
      return new Promise((resolve, reject) => {
        deleteSingleVideo({
          id
        })
          .then((res) => {
            if (res && res.code === 0) {
              resolve(true)
            } else {
              reject()
            }
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 关联单一视频循环形式
    fetchLinkRequest(id) {
      return new Promise((resolve, reject) => {
        linkSeries({
          video_id: id,
          series_id: this.series_id
        })
          .then((res) => {
            if (res && res.code === 0) {
              resolve(true)
            } else {
              reject()
            }
          })
          .catch(() => {
            reject()
          })
      })
    },
    save() {
      if (this.checkedList.length) {
        if (this.type === 'delete') {
          this.$confirm('确定删除这些视频?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              try {
                const requests = this.checkedList.map((index) =>
                  this.fetchRequest(index)
                )
                Promise.all(requests)
                  .then(() => {
                    this.cancel()
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    })
                    this.getData()
                  })
                  .catch(() => {
                    this.$message({
                      type: 'warning',
                      message: '删除失败，请重试'
                    })
                  })
              } catch (error) {
                console.error('An error occurred:', error)
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        } else {
          getCollectList()
            .then((res) => {
              if (res && res.code === 0) {
                this.options = (res?.data || []).map((i) => {
                  return {
                    label: i.title,
                    value: i.id
                  }
                })
              }
            })
            .then(() => {
              if (this.options.length) {
                this.visible = true
              } else {
                this.$message.error('暂无合集，请先创建合集')
              }
            })
            .catch(() => {
              this.$message.error('获取错误，请重试')
            })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '当前未选择视频'
        })
      }
    },
    confirmSave() {
      try {
        const requests = this.checkedList.map((index) =>
          this.fetchLinkRequest(index)
        )
        Promise.all(requests)
          .then(() => {
            this.visible = false
            this.cancel()
            this.$message({
              type: 'success',
              message: '关联成功!'
            })
            this.getData()
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '关联失败，请重试'
            })
          })
      } catch (error) {
        console.error('An error occurred:', error)
      }
    },
    // 删除单一视频
    deleteVideo(id) {
      this.$confirm('确定删除该视频?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除接口
          deleteSingleVideo({
            id
          })
            .then((res) => {
              if (res && res.code === 0) {
                this.getData()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'warning',
                message: '删除失败，请重试'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 选择-取消选择
    checkedPush(id) {
      const index = this.checkedList.indexOf(id)
      if (index !== -1) {
        this.checkedList.splice(index, 1)
      } else {
        this.checkedList.push(id)
      }
    },
    // 打开视频
    openVideo(url) {
      this.videoUrl = url
      this.videoShow = true
    },
    // 关闭视频弹窗
    closeMask() {
      this.videoShow = false
    },
    search() {
      this.videoList = this.dataList.filter((i) =>
        i.title.includes(this.searchVal)
      )
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
  text-align: left;
}
</style>
